/*
 *  Copyright 2008 Mark Ashworth <javameme@gmail.com>.
 * 
 *  Licensed under the GNU General Public License v3 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.gnu.org/licenses/gpl-3.0.html
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package xperiment.metaphor.service.user.impl;

import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
import xperiment.metaphor.model.people.user.User;
import xperiment.metaphor.persistence.filter.Expressions;
import xperiment.metaphor.persistence.filter.Query;
import xperiment.metaphor.service.impl.AbstractDomainService;
import xperiment.metaphor.service.user.UserService;

/**
 * User service
 * @author Mark Ashworth (javameme@gmail.com>
 * @version 1.0.0
 */
public class DefaultUserService extends AbstractDomainService implements UserService {
        
//    @Override
//    @Transactional
//    public User changePassword(String login, String password) {
//        User user = getUserDao().retrieveByName(login);
//        if (user != null) {
//            user.setPassword(password);
//        }
//        return user;
//    }

    @Override
    @Transactional(readOnly=true)
    public User retrieveByUserName(String userName) {
        
        Query query = 
                Query.forClass(User.class)
                .add(Expressions.ilike("username", userName));
        
        List results = retrieve(query);
        if (results.size() == 1 && (results.get(0) instanceof User)) {
            return (User) results.get(0);
        } else if (results.size() != 1) {
            logger.warn("Only one user with userName `{}` was expected, but {} were returned", userName, results.size());
        } else if (results.get(0) == null) {
            logger.warn("The result is was null");
        } else if (!(results.get(0) instanceof User)) {
            logger.warn("The result is not of type User.class, but {}", results.get(0).getClass());
        }
        return null;
    }
    
    @Override
    @Transactional(readOnly=true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        UserDetails user = (UserDetails) retrieveByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("The username " + username + " was not found");
        }
        return user;
    }
}
